<html>
<head>
  <!--<script src='https://cdn.wilddog.com/js/client/current/wilddog.js'></script>-->
  <script type="text/javascript" src="https://cdn.wilddog.com/sdk/js/2.0.0/wilddog-sync.js"></script>
  <script src="https://cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
  <link rel="stylesheet" type="text/css" href="/styles/example.css">
</head>
<body>
<div class="l-demo-container">
  <div class="header">
    <span class="circle"></span>
    <span class="circle"></span>
    <span class="circle"></span>
  </div>
  <div class="canvas-content">
    <canvas id="drawing-canvas" width="684" height="324"></canvas>  
  </div>
  <div id="colorholder">
      <span id="flush" onClick="return flush()">清理画板</span>
  </div>
</div>
<script>
    var myCanvas = document.getElementById('drawing-canvas');
  $(document).ready(function () {
    //创建全局对象
    var pixSize = 2, lastPoint = null, currentColor = "000", mouseDown = 0;

    //建立与wilddog的数据连接
    var config = {
      authDomain:"drawing.ckhuang.com",
      syncURL: "https://ckdrawing.wilddogio.com"
    };
    wilddog.initializeApp(config);
//    var pixelDataRef = new Wilddog('https://drawing.wilddogio.com/');
    var pixelDataRef = wilddog.sync().ref();
    //创建canvas绘图对象
    var myContext = myCanvas.getContext ? myCanvas.getContext('2d') : null;
    if (myContext == null) {
      alert("You must use a browser that supports HTML5 Canvas to run this demo.");
      return;
    }

    //创建绘图所能选择的颜色
    var colors = ["fff","000","eb3232","e6501e","fef200","32af5a","3c96e6","af20af"];
    for (c in colors) {
      var item = $('<div/>').css("background-color", '#' + colors[c]).addClass("colorbox");
      item.click((function () {
        var col = colors[c];
        return function () {
          currentColor = col;
        };
      })());
      item.appendTo('#colorholder');
    };

    //跟踪鼠标mousedown和mouseup 
    myCanvas.onmousedown = function () {
      mouseDown = 1;
    };
    myCanvas.onmouseout = myCanvas.onmouseup = function () {
      mouseDown = 0; lastPoint = null;
    };
    var rectArr = {};
    //根据鼠标的位置创建canvas对应的绘图
    var drawLineOnMouseMove = function(e) {
      if (!mouseDown) return;

      e.preventDefault();

      // 获取鼠标当前位置，定位对应的canvas上面的位置，如果是白色则删除此处所绘制过的图形
      var offset = $('canvas').offset();
      var x1 = Math.floor((e.pageX - offset.left) / pixSize - 1),
        y1 = Math.floor((e.pageY - offset.top) / pixSize - 1) + (16/ pixSize);
      var x0 = (lastPoint == null) ? x1 : lastPoint[0];
      var y0 = (lastPoint == null) ? y1 : lastPoint[1];
      var dx = Math.abs(x1 - x0), dy = Math.abs(y1 - y0);
      var sx = (x0 < x1) ? 1 : -1, sy = (y0 < y1) ? 1 : -1, err = dx - dy;

      while (true) {
        //更新数据到wilddog，如果是白色则删除对应数据
        var fillColor = currentColor === "fff" ? null : currentColor;
        myContext.fillStyle = "#" + currentColor;
        myContext.fillRect(parseInt(x0) * pixSize, parseInt(y0) * pixSize, pixSize, pixSize);
        rectArr[x0 +":" + y0] = fillColor;

        if (x0 == x1 && y0 == y1) break;
        var e2 = 2 * err;
        if (e2 > -dy) {
          err = err - dy;
          x0 = x0 + sx;
        }
        if (e2 < dx) {
          err = err + dx;
          y0 = y0 + sy;
        }
      }
      lastPoint = [x1, y1];
    };

    var setCanvasLine = function () {
        pixelDataRef.update(rectArr);
        rectArr = {};
    }

    $(myCanvas).mousemove(drawLineOnMouseMove);
    $(myCanvas).mousedown(drawLineOnMouseMove);
    $(myCanvas).mouseup(setCanvasLine);
	

     
    // 定义绘制图形的方法

    var drawPixel = function(snapshot) {
        var coords = snapshot.key().split(":");
        var color = snapshot.val();
        myContext.fillStyle = "#" + color;
        myContext.fillRect(parseInt(coords[0]) * pixSize, parseInt(coords[1]) * pixSize, pixSize, pixSize);
    };

    //定义删除wilddog数据的函数
    var clearPixel = function(snapshot) {
      var coords = snapshot.key().split(":");
      myContext.clearRect(parseInt(coords[0]) * pixSize, parseInt(coords[1]) * pixSize, pixSize, pixSize);
    };

    //根据wilddog数据改变调用不同的绘图方法
    pixelDataRef.on('child_added', drawPixel, function (error) {
      if(error.code == "TOO_BIG"){
        alert("画图信息数据过多 已自动清理画板");
        return flush();
      }
    });
    pixelDataRef.on('child_changed', drawPixel);
    pixelDataRef.on('child_removed', clearPixel);
  });

</script>
<script>
  function flush() {
      var config = {
          authDomain:"drawing.ckhuang.com",
          syncURL: "https://ckdrawing.wilddogio.com"
      };
      wilddog.initializeApp(config);
      var clearInstance = wilddog.sync().ref();
      clearInstance.remove();
  }
</script>
</body>
</html>
